const Koa = require('koa');
const path = require('path')
const koajwt = require('koa-jwt');
const bodyParser = require('koa-bodyparser');
const ejs = require('ejs');
const session = require('koa-session-minimal');
const MysqlStore = require('koa-mysql-session');
const config = require('./config/default.js');
const router = require('koa-router')
const views = require('koa-views')
// const koaStatic = require('koa-static')
const staticCache = require('koa-static-cache')
const {verToken} = require('./middlewares/token_verify')
const app = new Koa()


// session存储配置
const sessionMysqlConfig = {
    user: config.database.USERNAME,
    password: config.database.PASSWORD,
    database: config.database.DATABASE,
    host: config.database.HOST,
}

// 配置session中间件
// app.use(session({
//     key: 'USER_SID',
//     store: new MysqlStore(sessionMysqlConfig)
// }))
// 配置静态资源加载中间件
// app.use(koaStatic(
//   path.join(__dirname , './public')
// ))
app.use(async(ctx, next)=> {
    var token = ctx.headers.authorization;
    if(token == undefined){
        await next();
    }else{
        verToken(token).then((data)=> {
        //这一步是为了把解析出来的用户信息存入全局state中，这样在其他任一中间价都可以获取到state中的值
            ctx.state = {
                user:data
            };
        })
        await next();
    }
})
// 缓存
app.use(staticCache(path.join(__dirname, './public'), {
    dynamic: true
}, {
    maxAge: 365 * 24 * 60 * 60
}))
app.use(staticCache(path.join(__dirname, './images'), {
    dynamic: true
}, {
    maxAge: 365 * 24 * 60 * 60
}))

// 配置服务端模板渲染引擎中间件
// app.use(views(path.join(__dirname, './views'), {
//   extension: 'ejs'
// }))
// 错误处理
app.use((ctx, next) => {
    return next().catch((err) => {
        if (err.status === 401) {
            ctx.body = {
                code: 401,
                message: '登录过期！'
            };
        } else {
            throw err;
        }
    })
})
app.use(bodyParser({
    formLimit: '1mb'
}))
app.use(koajwt({
    secret: config.token_key
}).unless({
    path: [/\/signin/,/\/signup/,/\/oauth\/redirect/,/\/oauth\/weibo/]
}))
//  路由
app.use(require('./routers/oauth.js').routes())
app.use(require('./routers/signin.js').routes())
app.use(require('./routers/signup.js').routes())
app.use(require('./routers/posts.js').routes())
app.use(require('./routers/signout.js').routes())


app.listen(config.port)

console.log(`listening on port ${config.port}`)